import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/Home/HomeView.vue'
import SearchView from '../views/Search/SearchView.vue'
import DetailView from '../views/Detail/DetailView.vue'
import DirectoryView from '../views/DirectoryView.vue'
import ReaderView from '../views/Detail/ReaderView.vue'
import ClassifyDetailView from '../views/Detail/ClassifyDetailView.vue'
import LoginView from '../views/LoginView.vue'
import MyInfoView from '../views/MyInfoView.vue'
import BookShelfView from '../views/BookShelfView.vue'
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView
    },
    {
      path: '/search',
      name: 'search',
      component: SearchView
    },
    {
      path: '/book/:id',
      name: 'detail',
      component: DetailView
    },
    {
      path: '/book/:id/directory',
      name: 'directory',
      component: DirectoryView
    },
    {
      path: '/reader/book/:id',
      name: 'reader',
      component: ReaderView
    },
    {
      path: '/classify/id=:id',
      name: 'classify',
      component: ClassifyDetailView
    },
    {
      path: '/login',
      name: 'login',
      component: LoginView
    },
    {
      path: '/myinfo',
      name: 'myinfo',
      meta: {
        isNeedLogin: true
      },
      component: MyInfoView
    },
    {
      path: '/bookshelf',
      name: 'bookshelf',
      meta: {
        isNeedLogin: true
      },
      component: BookShelfView
    }
  ]
})
router.beforeEach((to, from, next) => {

  const isLogin = window.localStorage.getItem('token');

  if (to.meta.isNeedLogin) {

    if (isLogin) {
      next();
    } else {
      router.push({ path: "/login", query: { s: to.fullPath } })
    }
  } else {
    next();
  }
})
export default router
